//
//  AppDelegate.m
//  NaRiLSVMT
//
//  Created by jmsre on 14-8-8.
//  Copyright (c) 2014年 helloyouth.org. All rights reserved.
//
#import "AppDelegate.h"
#import "NRLSVMTViewController.h"
#import "FileManager.h"
#import "SettingViewController.h"
#import "UIViewController+MJPopupViewController.h"
#import "NetWorkRequestTest.h"
#import "MBProgressController.h"


extern  NSTimeInterval  oldCurrentTime;
static  NSString *pushServerIPText = nil;
static  NSString *pushSevicePORTText = nil;

@interface AppDelegate()<ITcpClient,UIAlertViewDelegate>
{
    
}
@end

@implementation AppDelegate
-(id)init
{
    self = [super init];
    return self;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    /********"设置信息"Cache var init***********/
    dSetupInfofm = [NSFileManager defaultManager];
    dSetupInfopath = [NSString stringWithFormat:@"%@%@%@",[FileManager getLibraryDirectory],@"/",@"SetupInfo.plist"];
    /**************read native Cache***************/
    //无 plist
    if(NO == [dSetupInfofm fileExistsAtPath:dSetupInfopath])
    {
        firstLoginSetupUI = 1;
        SettingViewController *settingViewController = [[SettingViewController alloc] initWithNibName:@"SettingViewController" bundle:nil];
        settingViewController.isLogin = NO;
        self.window.rootViewController = settingViewController;
    }
    else
    {
        NSData *data = [NSData dataWithContentsOfFile:dSetupInfopath];
        NSMutableDictionary *dicSetupInfo = [NSMutableDictionary dictionaryWithDictionary:[NSKeyedUnarchiver unarchiveObjectWithData:data]];

        kBaseUrl = [dicSetupInfo objectForKey:@"dataSeviceAddr"];
        pushServerIPText = [dicSetupInfo objectForKey:@"pushServerIP"];
        pushSevicePORTText = [dicSetupInfo objectForKey:@"pushSevicePORT"];
        
        [NetWorkRequestTest networkTestConnected];
        
        TcpClient *tcp = [TcpClient sharedInstance];
        [tcp setDelegate_ITcpClient:self];
        if(!tcp.asyncSocket.isConnected)
        {
            NSString *HOST = pushServerIPText;
            NSString *port = pushSevicePORTText;
            [tcp openTcpConnection:HOST port:[port intValue]];
        }
        /*************************************/
        //校验连接TCP
        /*************************************/
        sleep(1);
        dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            sleep(1);
            if(tcp.asyncSocket.isConnected)
            {
                /*********连接成功后，发心跳包**********/
                NSString *requestStr = [NSString stringWithFormat:@"{\"messageData\":\"%@\",\"messageType\":%d}",@"",6];
                [tcp sendTestPacketData:requestStr];
                
                // Override point for customization after application launch.
                NRLSVMTViewController   *loginViewController = [[NRLSVMTViewController alloc] initWithNibName:@"NRLSVMTViewController" bundle:nil];
                self.window.rootViewController = loginViewController;
            }
            else
            {
                firstLoginSetupUI = 2;
                SettingViewController *settingViewController = [[SettingViewController alloc] initWithNibName:@"SettingViewController" bundle:nil];
                settingViewController.isLogin = NO;
                self.window.rootViewController = settingViewController;
            }
        });
    }
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
//    NSArray *array = @[@1,@2,@3,@4,@10];
//    NSNumber *transactionAverage = [array valueForKeyPath:@"@avg.floatValue"];
//    NSLog(@"avg:%@",transactionAverage);
//    NSArray *results = [array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id  _Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
//        return [evaluatedObject floatValue] > transactionAverage.floatValue;
//    }]];
//    NSLog(@"count:%d",(int)results.count);

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    //testConnected() Call var init....
//    NetWorkRequestTest  *networkRequest = [[NetWorkRequestTest alloc] init];
//    [networkRequest networkTestConnected];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


#pragma mark -
#pragma mark ITcpClient

/**发送到服务器端的数据*/
-(void)OnSendDataSuccess:(NSString*)sendedTxt;
{
    //self.tfRecived.text = [NSString stringWithFormat:@"%@\r\nsended-->:%@\r\n",self.tfRecived.text,sendedTxt];
}

/**收到服务器端发送的数据*/
-(void)OnReciveData:(NSString*)recivedTxt;
{
    //self.tfRecived.text = [NSString stringWithFormat:@"%@\r\n-->recived:%@\r\n",self.tfRecived.text,recivedTxt];
    
    /*****************这里做信号灯的判断和断网提示**********************/
    NSDateFormatter *dateFormat =[[NSDateFormatter alloc]init];
    [dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CH"]];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSTimeInterval  currentTime = [[NSDate date] timeIntervalSince1970];
    
    if(0 != oldCurrentTime)
    {
        if(currentTime - oldCurrentTime > 20 && currentTime - oldCurrentTime<60)
        {
            isHaveDisconnect = YES;
            PostNoticeObserver(@"NetworkSignalNotice", @(1));
        }
        else if(currentTime - oldCurrentTime > 60)
        {
            //关闭定时器
            [[TimerDownImage sharedInstance] stopTimerflushThumb];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"服务端网络出错!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            alert.delegate = self;//断掉后，重连
            [alert show];
            isHaveDisconnect = YES;
            PostNoticeObserver(@"NetworkSignalNotice", @(1));
            //在这里把TCP 完全断掉
        }
        else
        {
            if(isHaveDisconnect == YES)
            {
                PostNoticeObserver(@"NetworkSignalNotice", @(0));
            }
        }
    }
    oldCurrentTime = currentTime;
    /**************************************************************/
    
    NSInteger   lastLengh = recivedTxt.length;
    NSRange subIndex = [recivedTxt rangeOfString:@"\r\n"];
    while(!(subIndex.location == NSNotFound) && (lastLengh>0))
    {
        NSString *subStr = [recivedTxt substringWithRange:NSMakeRange(0, subIndex.location)];
        NSLog(@"%@ 根据服务端反馈的命令，来做出响应的处理",subStr);
        
        NSRange boolSendNotice;
        boolSendNotice = [subStr rangeOfString:@"GetEvents"];
        if(!(boolSendNotice.location == NSNotFound))
        {
            PostNoticeObserver(NoticeKey_TcpGetEvents, subStr);
        }
        
        //播放器关掉  刷新数据
        boolSendNotice = [subStr rangeOfString:@"DeviceGetScreenInfo"];
        
        if(!(boolSendNotice.location == NSNotFound))
        {
            PostNoticeObserver(NoticeKey_TcpDeviceGetScreen, subStr);
        }
        
        boolSendNotice = [subStr rangeOfString:@"UpdateClient"];
        
        if(!(boolSendNotice.location == NSNotFound))
        {
            PostNoticeObserver(NoticeKey_TcpUpateClient, subStr);
        }
        
        //        boolSendNotice = [subStr rangeOfString:@"DeviceGetScreenInfo"];
        //
        //        if(!(boolSendNotice.location == NSNotFound))
        //        {
        //            PostNoticeObserver(@"NoticeKey_TcpGetEvents_String", subStr);
        //        }
        ////////////////////////////////////////////////////////////////////
        
        lastLengh -= (subIndex.location+2);
        if(lastLengh > 0)
        {
            subIndex = [[recivedTxt substringWithRange:NSMakeRange(subIndex.location+2, lastLengh)] rangeOfString:@"\r\n"];
        }
    }
    
    
    NSLog(@"%@",recivedTxt);
}

/**socket连接出现错误*/
-(void)OnConnectionError:(NSError *)err;
{
    //self.tfRecived.text = [NSString stringWithFormat:@"%@\r\n\r\n**** network error! ****\r\n",self.tfRecived.text];
//    [[MBProgressController sharedInstance] showTipsOnlyText:@"**** 网络错误! ****"
//                                                   AndDelay:1.5];
//    [[MBProgressController sharedInstance] hide];
    return;
}

#pragma mark-
#pragma mark- UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    TcpClient *tcp = [TcpClient sharedInstance];
    [tcp setDelegate_ITcpClient:self];
    if(!tcp.asyncSocket.isConnected)
    {
        NSString *HOST = pushServerIPText;
        NSString *port = pushSevicePORTText;
        [tcp openTcpConnection:HOST port:[port intValue]];
    }
    /*************************************/
    //TCP建立成功后，开启一个线程，不停的发心跳包，每30秒发一个，如果服务器没有响应，则认为断线，则重新连接.
    /*************************************/
    dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(1);
        if(tcp.asyncSocket.isConnected)
        {
            /*********连接成功后，发心跳包**********/
            NSString *requestStr = [NSString stringWithFormat:@"{\"messageData\":\"%@\",\"messageType\":%d}",@"",6];
            [tcp sendTestPacketData:requestStr];
        }
        else
        {
            [[MBProgressController sharedInstance] showTipsOnlyText:@"请进行测试连接确认连接成功"
                                                           AndDelay:1.5];
            [[MBProgressController sharedInstance] hide];
            return;
        }
    });
}
@end
